package com.xyz.apis.modules.comm.oauth2;


import com.xyz.admin.common.entity.EvUserEntity;
import com.xyz.apis.repository.UserTokenRepository;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 认证
 *
 *
 *
 * @date 2017-05-20 14:00
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    private UserTokenRepository userTokenRepository;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(null);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();
        //根据accessToken，查询用户信息
        EvUserEntity evUserEntity = userTokenRepository.getToken(accessToken);
        //token失效
        if(evUserEntity == null){
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }
        //账号锁定
        if(evUserEntity.getStatus() != null && evUserEntity.getStatus() == 0){
            userTokenRepository.deleteToken(accessToken,evUserEntity.getUserid());
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(evUserEntity, accessToken, getName());
        return info;
    }
}
